package cn.demoa.myapplication;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.Toast;

import java.util.ArrayList;

public class StuAdapter extends BaseAdapter {
    private ArrayList<Student> studentArrayList;
    private Context context;
    private int count = 0;
    private IOnDelListener listener;


    public StuAdapter(Context context, ArrayList<Student> studentArrayList, IOnDelListener listener) {
        this.context = context;
        this.studentArrayList = studentArrayList;
        this.listener = listener;
    }

    @Override
    public int getCount() {
        return studentArrayList.size();
    }

    @Override
    public Object getItem(int i) {
        return studentArrayList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        Log.e("stuAdapter", "getView" + i + "count=" + count);

        // 先判断view是不是空 非空可以复用 不需要重新构建 节省内存
        if (view == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            view = layoutInflater.inflate(R.layout.my_list_item, viewGroup, false);
            count++;

            //使用Holder保存子组件 避免每次使用时重复find
            StuViewHolder viewHolder = new StuViewHolder();
            viewHolder.headImg = view.findViewById(R.id.head_view);
            viewHolder.nameView = view.findViewById(R.id.name_view);
            viewHolder.ageView = view.findViewById(R.id.age_view);
            viewHolder.delView = view.findViewById(R.id.del_view);
            view.setTag(viewHolder);
        }

        Student stu = studentArrayList.get(i);

        StuViewHolder viewHolder = (StuViewHolder) view.getTag();

        viewHolder.headImg.setImageResource(studentArrayList.get(i).getImgid());
        viewHolder.nameView.setText(studentArrayList.get(i).getName());
        viewHolder.ageView.setText(String.valueOf(studentArrayList.get(i).getAge()));

        //鼠标点击del删除学生
        viewHolder.delView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.del(i);
            }
        });

        return view;
    }

    /*返回搜索结果*/
    public void changeData(ArrayList<Student> studentArrayList) {
        this.studentArrayList = studentArrayList;
        notifyDataSetChanged();
    }
}
